package com.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;

import static com.util.Util.getRealPath;

/**
 * 上传文件夹
 *
 * @author wang_
 * @version 2024.3.4.1
 * @description
 * @date 2025/7/10
 */
public class FileTool {
	protected static final Logger LOG = LogManager.getLogger(FileTool.class);
	/// 文件上传路径
	private final          String uploadFilePath;
	/// 文件夹
	private final          File   file;
	
	/**
	 * 构造方法
	 *
	 * @param session session
	 * @param path    路径
	 */
	public FileTool(HttpSession session, String path) {
		this(getRealPath(session, path));
	}
	
	public FileTool(String uploadFilePath) {
		this.uploadFilePath = uploadFilePath;
		File file = new File(this.uploadFilePath);
		// 判断文件夹是否存在
		if (!file.exists()) {
			LOG.error("{}文件夹不存在！正在尝试创建", this.uploadFilePath);
			// 创建文件夹
			if (file.mkdirs()) {
				LOG.info("{}文件夹创建成功！", this.uploadFilePath);
			} else {
				LOG.error("{}文件夹创建失败！", this.uploadFilePath);
			}
		}
		this.file = file;
	}
	
	/**
	 * 构造方法
	 *
	 * @param request request
	 * @param path    路径
	 */
	public FileTool(HttpServletRequest request, String path) {
		this(getRealPath(request, path));
	}
	
	/// 获取文件
	public File getFile() {
		return file;
	}
	
	/// 获取上传文件路径
	public String getUploadFilePath() {
		return uploadFilePath;
	}
}
